import { defineStore } from "pinia";
import type {
  FlowExportObject,
} from "@vue-flow/core";

interface CommentState {
  data: { cid: number; comments: CommentPostType[] }[];
  sharedFLowObj: FlowExportObject | null;
}
interface CommentAction {
  addComment: (ciid: number, comment: CommentPostType) => void;
  addComments: (ciid: number, comments: CommentPostType[]) => void;
  removeComment: (ciid: number, comment: CommentPostType) => void;
  doSetSharedFlowObj: (flow: FlowExportObject) => void;
  doClearSharedFlowObj: () => void;
  // bridge
  loadSharedFlowObjFn?: (flow: FlowExportObject) => void;
}

// eslint-disable-next-line ts/consistent-type-definitions
type CommentGetter = {
  getComments: (state: CommentState) => (cid: number) => CommentPostType[];
};
export const useMyCommentStore = defineStore<
  "myCommentStore",
  CommentState,
  CommentGetter,
  CommentAction
>({
  id: "myCommentStore",
  state: () => ({
    data: [
      { cid: 1, comments: [] },
      { cid: 2, comments: [] },
      { cid: 3, comments: [] },
      { cid: 4, comments: [] },
    ],
    sharedFLowObj: null,
  }),
  getters: {
    getComments: state => (cid) => {
      const index = state.data.findIndex(v => v.cid === cid);
      return index === -1 ? [] : state.data[index].comments;
    },
  },
  actions: {
    addComment(ciid: number, comment: CommentPostType) {
      const index = this.data.findIndex(v => v.cid === ciid);
      if (index === -1) 
        this.data.push({ cid: ciid, comments: [comment] });
      else this.data[index].comments.push(comment);
    },
    addComments(ciid: number, comments: CommentPostType[]) {
      const index = this.data.findIndex(v => v.cid === ciid);
      if (index === -1) 
        this.data.push({ cid: ciid, comments });
      else this.data[index].comments = comments;
    },
    removeComment(ciid: number, comment: CommentPostType) {
      const index = this.data.findIndex(v => v.cid === ciid);
      if (index === -1) 
        return;
      this.data[index].comments = this.data[index].comments.filter(
        v => v !== comment,
      );
    },
    doSetSharedFlowObj(flow: FlowExportObject) {
      this.sharedFLowObj = flow;
    },
    doClearSharedFlowObj() {
      this.sharedFLowObj = null;
    },
  },
  persist: {
    storage: persistedState.sessionStorage,
  },
});
